package com.xlink.action;

import com.xlink.domain.XlinkUser;
import com.xlink.service.XlinkUserService;
import org.moon.base.action.BaseAction;
import org.moon.log.service.LogService;
import org.moon.message.WebResponse;
import org.moon.rbac.domain.User;
import org.moon.rbac.domain.annotation.LoginRequired;
import org.moon.rbac.domain.annotation.WebUser;
import org.moon.rest.annotation.Get;
import org.moon.rest.annotation.Post;
import org.moon.rest.annotation.Put;
import org.moon.utils.Maps;
import org.moon.utils.Objects;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * Created by Cathy on 2015/12/19.
 */
@Controller("xlinkUserAction")
@RequestMapping("/users")
public class UserAction extends BaseAction {

    @Resource
    private LogService logService;

    @Resource
    private XlinkUserService xlinkUserService;

    /**
     * 显示注册页面
     * @param from
     * @return
     */
    @Get("/register")
    public ModelAndView showRegisterPage(@RequestParam(value = "from", defaultValue = "") String from) {
        return new ModelAndView("pages/register", "from", from);
    }

    /**
     * 用户注册
     * @param userName
     * @param password
     * @param email
     * @return
     */
    @Post("/register/validate")
    @ResponseBody
    public WebResponse register(@RequestParam("userName") String userName,
                                @RequestParam("password") String password,
                                @RequestParam("email")String email,
                                @RequestParam("captcha")String captcha,
                                HttpSession session) {
         if(xlinkUserService.isUserNameExists(userName)){
              return WebResponse.fail("用户名存在");
         }
         if(captcha.equalsIgnoreCase(session.getAttribute("code").toString())){
              xlinkUserService.register(userName, password, email);
             return WebResponse.success("注册成功");
         }else {
              return WebResponse.fail("验证码错误");
         }
    }
    /**
     * 检查邮箱是否被注册
     * @param email
     * @return
     */
    @Get("/email/exist")
    @ResponseBody
    public WebResponse checkUserName(@PathVariable("email")String email){
        return WebResponse.success(Maps.mapItSO("exist", xlinkUserService.isemailRegistered(email)));
    }

    /**
     * 显示登陆页面
     * @param from
     * @return
     */
    @Get("/login")
    public ModelAndView showLoginPage(@RequestParam(value = "from", defaultValue = "") String from) {
        return new ModelAndView("pages/login", "from", from);
    }

    /**
     * 用户登录
     * @param userName
     * @param password
     * @param request
     * @return
     */
    @Post("/login/validate")
    @ResponseBody
    public WebResponse login(@RequestParam("userName")String userName,
                             @RequestParam("password")String password,
                             HttpServletRequest request){
        if(!xlinkUserService.isUserNameExists(userName)){
            return WebResponse.fail("用户名不存在");
        }else{
            XlinkUser user = xlinkUserService.login(userName,password);
            if(Objects.isNull(user)){
                return WebResponse.fail("fail to login");
            }
            request.getSession().setAttribute(User.CURRENT_USER_ID, user.getId());
            request.getSession().setAttribute("userId", user.getId());
            request.getSession().setAttribute("userName",userName);

            return WebResponse.success("登录成功");
        }
    }

    /**
     * 密码匹配，用于修改密码
     * @param user
     * @param newPassword
     * @return
     */
    @LoginRequired
    @ResponseBody
    @Get("/~/matchOldPassword")
    public WebResponse matchOldPassword(@WebUser User user, @RequestParam("password") String newPassword) {
        if (user.getPassword().equals(newPassword)) {
            return WebResponse.build().setSuccess(true);
        } else {
            return WebResponse.build().setSuccess(false);
        }
    }

    /**
     * 修改密码
     * @param user
     * @param newPassword
     * @return
     */
    @LoginRequired
    @Post("/~/doChangePassword")
    @ResponseBody
    public WebResponse changePassword(@WebUser User user, @RequestParam("password") String newPassword) {
        user.setPassword(newPassword);
        user.sync(user.encryptPassword().update());
        return WebResponse.build().setSuccess(true);
    }

    /**
     * 账户设置
     * @param user
     * @return
     */
    @Put("/complete")
    @LoginRequired
    @ResponseBody
    public WebResponse complete(@WebUser User user, @RequestBody Map<String,Object> params){
        params.put("id",user.getId());
        xlinkUserService.updateUser(params);
        return WebResponse.success();
    }

    /**
     * 登出
     * @param request
     * @return
     */
    @Post("/logout")
    @LoginRequired
    @ResponseBody
    public WebResponse signOut(HttpServletRequest request){
        request.getSession().invalidate();
        return WebResponse.success("sign out successfully.");
    }

    /**
     * 根据id获取用户信息
     * @param id
     * @return
     */
    @Get("/get/{id}")
    @ResponseBody
    @LoginRequired
    public WebResponse get(@PathVariable("id")Long id){
        return WebResponse.success(xlinkUserService.getById(id));
    }

}


